import { createReducer, createActions } from 'reduxsauce'
import { AsyncStorage } from 'react-native'
import Immutable from 'seamless-immutable'

/* ------------- Types and Action Creators ------------- */

const { Types, Creators } = createActions({
  updateUserRequest: ['token', 'field', 'value'],
  updateUserSuccess: ['payload'],
  updateUserFailure: null,
  userRequest: ['token', 'deviceId'],
  userSuccess: ['payload'],
  userFailure: null,
  logout: null,
})

export const UserTypes = Types
export default Creators

/* ------------- Initial State ------------- */

export const INITIAL_STATE = Immutable({
  deviceId: null,
  fetching: null,
  payload: null,
  error: null
})

/* ------------- Reducers ------------- */
// logout
export const logout = (state) => {
  AsyncStorage.clear()
  return INITIAL_STATE
}

// update field value
export const updateRequest = (state, action) =>
  state.merge({fetching:true, error:null})

export const updateSuccess = (state, {payload}) =>
  state.merge({fetching:false, error:false, payload:payload})

export const updateFailure = (state) =>
  state.merge({fetching:false,error:true})

// request the data from an api
export const request = (state, { token, deviceId }) =>
  state.merge({ fetching: true, error: null, deviceId })

// successful api lookup
export const success = (state, action) => {
  const { payload } = action
  return state.merge({ fetching: false, error: false, payload })
}

// Something went wrong somewhere.
export const failure = state =>
  state.merge({ fetching: false, error: true, payload: null })

/* ------------- Hookup Reducers To Types ------------- */

export const reducer = createReducer(INITIAL_STATE, {
  [Types.UPDATE_USER_REQUEST]: updateRequest,
  [Types.UPDATE_USER_SUCCESS]: updateSuccess,
  [Types.UPDATE_USER_FAILURE]: updateFailure,
  [Types.USER_REQUEST]: request,
  [Types.USER_SUCCESS]: success,
  [Types.USER_FAILURE]: failure,
  [Types.LOGOUT]: logout,
})
